import logging

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp

class Action(webapp.RequestHandler):
  def isValidUserModel(self, model):
    return model != None or users.get_current_user() == model.author

class Put(Action):
  actionURL = 'put'
  
  def __init__(self, model_type):
    self.model_type = model_type
  
  def post(self):
    if users.get_current_user():
      key = self.request.get('key')
      model = None
      
      if key != None and key != '':
        model = self.model_type.get(key)
        
        if not self.isValidUserModel(model):
          logging.debug("!!!")
      else:
        model = self.model_type()
      
      model.author = users.get_current_user()
      
      for argument in self.request.arguments():
        if argument.lower() != 'key':
          model.__setattr__(argument, self.request.get(argument))
      
      model.put()
      
    self.redirect('/')

class Delete(Action):
  actionURL = 'delete'
  
  def __init__(self, model_type):
    self.model_type = model_type
  
  def get(self):
    if users.get_current_user():
      model = self.model_type.get(self.request.get('key'))
      
      if self.isValidUserModel(model):
        model.delete()
      
    self.redirect('/')
